import {BakFileFormat, getApp, loadSettings, MessageType, msgTitleMap, writeSetting2File} from "../common/utils";
import {BrowserWindowConstructorOptions, BrowserWindow, dialog, Notification, WebPreferences} from "electron";
import  fs from "node:fs";
import remote = require("@electron/remote/main")

export function showMessageInMain(msg: string, type: MessageType) {
    if (!Notification.isSupported()) {
        dialog.showMessageBox({
            title: msgTitleMap[type],
            message: msg,
        }).then(r => {
        });
        return;
    }
    const no = new Notification({
        title: msgTitleMap[type],
        closeButtonText: "关闭",
        body: msg
    });
    no.show();
}

export function importHosts(window: BrowserWindow) {
    dialog.showOpenDialog(window, {
        title: "选择从mHosts导出的文件",
        message: "您可以选择从mHosts，mHosts.Net导出的文件，如果导入的hosts已经存在且内容和现有的不一样， 导入的会覆盖现在有的",
        buttonLabel: "导入",
        filters: [
            {extensions: ["mhosts", "hosts", "host"], name: "mHosts备份文件"},
            {extensions: ["json"], name: "JSON文件"}
        ]
    }).then(res => {
        if (res.canceled) return;
        const fileName = res.filePaths[0];

        try {
            const json: BakFileFormat = JSON.parse(
                fs.readFileSync(fileName, {encoding: "utf-8"})
            );
            const settings = loadSettings();
            const current = settings.hosts;
            let cover = 0;
            let newHost = 0;
            json.hosts.filter(host => {
                if ((host.id in current) && host.content !== current[host.id].content) {
                    cover++;
                    return true;
                }
                if (!(host.id in current)) {
                    newHost++;
                    return true;
                }
                return false;
            }).forEach(host => {
                current[host.id] = {...host, isActive: false}
            });
            if (!cover && !newHost) {
                showMessageInMain("导入的文件和当前一致，无需导入", MessageType.success);
                return;
            }
            writeSetting2File({...settings, hosts: current});
            showMessageInMain(
                `成功导入${cover + newHost}条数据，新建${newHost}条，覆盖${cover}条`,
                MessageType.success
            )
        } catch (e) {
            dialog.showErrorBox("文件解析失败", `选择的文件解析失败: ${e.message}`)
        }
    })
}

export function exportHosts(window: BrowserWindow) {
    dialog.showSaveDialog(window, {
        title: "保存Hosts",
        message: "选择保存位置",
        filters: [
            {extensions: ["mhosts"], name: "mHosts备份文件"},
        ]
    }).then(res => {
        if (res.canceled) return;
        const {hosts} = loadSettings();
        fs.writeFile(
            res.filePath,
            JSON.stringify({
                saveTime: Date.now(),
                hosts: Object.values(hosts),
                mHostsVersion: getApp().getVersion()
            }),
            {encoding: "utf-8"},
            () => {
                showMessageInMain("备份成功", MessageType.success)
            }
        );
    });
}

export function newBrowserWindow({webPreferences, ...options}: BrowserWindowOptions): BrowserWindow {
    if (webPreferences?.enableRemoteModule) {
        webPreferences.contextIsolation = false;
    }
    const win = new BrowserWindow({...options, webPreferences});
    if (webPreferences?.enableRemoteModule) {
        webPreferences.contextIsolation = false;
        remote.enable(win.webContents);
    }
    return win;
}

export interface BrowserWindowOptions extends BrowserWindowConstructorOptions {
    webPreferences: WebPreferences & { enableRemoteModule?: boolean }
}